//---------------------------------------------------------------------------
#include "http_cookie.h"

//---------------------------------------------------------------------------

void http_cookie::ParseHeader(std::string header) {
        int pos = -1;
        std::string TempHeader = header;
        std::string CookieStr;
        std::string Name;
        std::string Value;
        while(1) {
                pos = TempHeader.find("Set-Cookie: ",0);
                if (pos == -1) break;
                TempHeader.erase(0,pos+12);
                pos = TempHeader.find("\r\n",0);
                CookieStr = TempHeader.substr(0,pos+2);
                while(1) {
                        pos = CookieStr.find("=",0);
                        if (pos == -1) break;
                        Name = CookieStr.substr(0,pos);
                        CookieStr.erase(0,pos+1);
                        pos = CookieStr.find(";",0);
                        if (pos == -1) {
                                pos = CookieStr.find("\r\n",0);
                        }
                        if (pos != -1) {
                                Value = CookieStr.substr(0,pos);
                                CookieStr.erase(0,pos+2);
                                if (Name.compare("path") != 0 && Name.compare("expires") != 0 && Name.compare("domain") != 0) {
                                        if (this->Exist(Name)) {
                                                this->Update(Name,Value);
                                        }
                                        else {
                                                this->Add(Name,Value);
                                        }
                                }
                        }
                }
        }
}

std::string http_cookie::make_str() {
        int str_count = this->GetCount();
        std::string result;
        if (str_count > 0) {
                std::string name;
                std::string value;
                for (int i = 0; i<str_count; i++) {
                        if (i > 0) result.append("; ");
                        name = this->GetName(i);
                        value = this->GetValue(i);
                        result.append(name);
                        result.append("=");
                        result.append(value);
                }
        }
        return result;
}

